package com.sean.reverse.service.impl;

import com.sean.reverse.exception.CookieErrorException;
import com.sean.reverse.service.ReverseService;
import com.sean.reverse.util.SmsComponent;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sean
 * @createTime 2022/4/11 23:02
 * @description
 */
@Service("reverseServiceImpl")
public class ReverseServiceImpl implements ReverseService {

    @Autowired
    SmsComponent smsComponent;

    private final Map<String, Integer> timeSlotMap = new HashMap<String, Integer>(){
        {
            put("8-9",1);
            put("9-10",2);
            put("10-11",3);
            put("11-12",4);
            put("12-13",5);
            put("13-14",6);
            put("15-16",7);
            put("16-17",8);
            put("17-18",9);
            put("18-19",10);
            put("19-20",11);
            put("20-21",12);
            put("21-22",13);
        }
    };

    @Override
    public String reverse(String qiuguanId, String cookie, String timeSlot1, String timeSlot2, boolean isReverse, String phone) {
        int reverseNum = -1;
        int timeSlotNum1 = timeSlotMap.getOrDefault(timeSlot1, 13);
        int timeSlotNum2 = timeSlotMap.getOrDefault(timeSlot2, -1);
        //预约7号场
        try {
            String reverseBadminton = reverseBadminton(qiuguanId,7, timeSlotNum1, timeSlotNum2, cookie, isReverse);
            if(reverseBadminton.equals("参数错误")){
                return "预约失败：Cookie失效";
            }
            if(reverseBadminton.equals("")){
                reverseNum = 7;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //预约其他场地
        for (int i = 9; i >= 1; i--) {
            try {
                String reverseBadminton = reverseBadminton(qiuguanId, i, timeSlotNum1, timeSlotNum2, cookie, isReverse);
                if(reverseNum == -1 && reverseBadminton.equals("")){
                    reverseNum = i;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(reverseNum == -1){
            return "预约失败";
        }else {
            if(isReverse){
                //发短信
                smsComponent.sendMessage(String.valueOf(reverseNum),
                        timeSlotNum2!=-1 ? timeSlot1+","+timeSlot2 : timeSlot1,
                        phone);
            }
            return "成功预约：" + reverseNum + "号场";
        }
    }

    private static String reverseBadminton(String qiuguanId, int courtId, int timeSlot1, int timeSlot2, String cookie, boolean isReverse) throws Exception {
        String[] changdi = new String[]{"15418","15419","15420","15421","15422","15423","15424","15425","15426"};
        String[] changdi3 = new String[]{"15427","15428","15429","15430","15431"};
        String[] shijianduan = new String[]{"01","02","03","04","05","06","08","09","10","11","12","13","14"};
        SimpleDateFormat sdfDay = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyyMMdd HH:mm:ss");

        Date today = new Date();
        String reverseDay;
        if(isReverse){//预约，
            reverseDay = sdfDay.format(today.getTime() + 1000*60*60*24);
        }else{//不预约，直接抢最新一天的场地
            String todayDay = sdfDay.format(today.getTime());
            long tenTime = 0;
            try {
                tenTime = sdfTime.parse(sdfDay.format(today.getTime()) + " 10:00:00").getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(today.getTime() > tenTime){//超过了今天的十点，明天是最新的，抢明天的场地
                reverseDay = sdfDay.format(today.getTime() + 1000*60*60*24);
            }else{//没有过今天的十点，今天是最新的，抢今天的场地
                reverseDay = todayDay;
            }
        }
//        System.out.println(tomorrow);

        String chang = "15424";
        if(qiuguanId.equals("5982")){
            chang = changdi[courtId-1];
        }else if(qiuguanId.equals("5991")){
            courtId = Math.min(courtId, 5);
            chang = changdi3[courtId-1];
        }
        String shi1 = shijianduan[timeSlot1-1], shi2 = "-1";
        if(timeSlot2 > 0){
            shi2 = shijianduan[timeSlot2-1];
        }

        //1.创建一个HttpClient对象
        HttpClient client = HttpClients.createDefault();
        //2.创建一个请求对象(GET/POST/PUT/DELETE...)
        String url = "http://reservation.bupt.edu.cn/index.php/Wechat/Booking/confirm_booking?" +
                "area_id=" + qiuguanId +
                "&td_id=" + chang + "_" + reverseDay + shi1 + (timeSlot2 > 0 ? "," + chang + "_" + reverseDay + shi2 : "") +
                "&query_date=" + reverseDay +
                "&country_id=0";
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Cookie","PHPSESSID="+ cookie +"; think_language=zh-cn");
        httpGet.setHeader("Referer","https://reservation.bupt.edu.cn/index.php/Wechat/Booking/choose_template/template/1/area_id/"+ qiuguanId +"/country_id/0/from/");

        //3.发送请求
        HttpResponse response = client.execute(httpGet);
        //4.获取结果
        String result = EntityUtils.toString(response.getEntity());
        if(result.equals("参数错误")){
            return result;
        }

        int start = result.lastIndexOf("form_valid_code_value") + 30;
        if(start < 30){
            int first = result.lastIndexOf("<div class=\"text\">") + 17;
            int last = result.lastIndexOf("<script type=\"text/javascript\">") - 17;
            String s = shi2.equals("-1") ? "" : "-时间" + shi2;
            if(last < first || last < 0){
                System.out.println(reverseDay + "-场地" + courtId + "-时间" + shi1 + s + "-time" + sdfTime.format(new Date()) + ":" + result);
            }else{
                System.out.println(reverseDay + "-场地" + courtId + "-时间" + shi1 + s + "-time" + sdfTime.format(new Date()) + ":" +result.substring(first,last));
            }
            return result;
        }
        String form_valid_code_value = result.substring(start, start + 10);
//        System.out.println(form_valid_code_value);

        int priceStart = result.lastIndexOf("no_card_price") + 22;
        if(priceStart < 22){
            int first = result.lastIndexOf("<div class=\"text\">") + 17;
            int last = result.lastIndexOf("<script type=\"text/javascript\">") - 17;
            String s = shi2.equals("-1") ? "" : "-时间" + shi2;
            if(last < first || last < 0){
                System.out.println(reverseDay + "-场地" + courtId + "-时间" + shi1 + s + "-time" + sdfTime.format(new Date()) + ":" + result);
            }else{
                System.out.println(reverseDay + "-场地" + courtId + "-时间" + shi1 + s + "-time" + sdfTime.format(new Date()) + ":" +result.substring(first,last));
            }
            return result;
        }
        if(priceStart + 2 >= result.length()){
            System.out.println(result);
        }
        String price = result.substring(priceStart, priceStart + 2);
//        System.out.println(price);
//        System.out.println("============>"+result);

        //预约
        HttpPost httpPost = new HttpPost("http://reservation.bupt.edu.cn/index.php/Wechat/Register/register_show");
        httpPost.setHeader("Cookie","PHPSESSID="+ cookie +"; think_language=zh-cn");
        httpPost.setHeader("Referer",httpGet.getURI().toString());
        httpPost.setHeader("Accept-Language","zh-CN,zh-Hans;q=0.9");
        httpPost.setHeader("Origin","http://reservation.bupt.edu.cn");
        httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpPost.setHeader("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)  Mobile/15E148 wxwork/4.0.3 MicroMessenger/7.0.1 Language/zh ColorScheme/Dark");
        httpPost.setHeader("Host","reservation.bupt.edu.cn");
        httpPost.setHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundaryqgcYEAGsqV5oE88g");
//        httpPost.setHeader("Content-Length","3747");

        String body = "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"form_valid_code_value\"\n" +
                "\n" +
                form_valid_code_value +"\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"custom_class_ids\"\n" +
                "\n" +
                "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"country_id\"\n" +
                "\n" +
                "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"country_name\"\n" +
                "\n" +
                "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"area_id\"\n" +
                "\n" +
                qiuguanId + "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"area_name\"\n" +
                "\n" +
                "羽毛球场\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"room_id\"\n" +
                "\n" +
                chang +"\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"room_name\"\n" +
                "\n" +
                "羽毛球场"+courtId+"号\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"device_id\"\n" +
                "\n" +
                "0\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"selected_device_name\"\n" +
                "\n" +
                "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"soft_id\"\n" +
                "\n" +
                "0\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"selected_soft_name\"\n" +
                "\n" +
                "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"time_id\"\n" +
                "\n" +
                reverseDay + shi1 + (shi2.equals("-1") ? "" : " "+reverseDay+shi2) + "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"total_amount\"\n" +
                "\n" +
                price + "\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr\"\n" +
                "\n" +
                "Array\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"packages_showing_type\"\n" +
                "\n" +
                "2\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"mixed_payment_type\"\n" +
                "\n" +
                "wechat_pay\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"to_use_vip_id\"\n" +
                "\n" +
                "0\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_1\"\n" +
                "\n" +
                "08:00-09:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_2\"\n" +
                "\n" +
                "09:00-10:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_3\"\n" +
                "\n" +
                "10:00-11:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_4\"\n" +
                "\n" +
                "11:00-12:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_5\"\n" +
                "\n" +
                "12:00-13:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_6\"\n" +
                "\n" +
                "13:00-14:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_7\"\n" +
                "\n" +
                "14:00-15:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_8\"\n" +
                "\n" +
                "15:00-16:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_9\"\n" +
                "\n" +
                "16:00-17:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_10\"\n" +
                "\n" +
                "17:00-18:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_11\"\n" +
                "\n" +
                "18:00-19:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_12\"\n" +
                "\n" +
                "19:00-20:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_13\"\n" +
                "\n" +
                "20:00-21:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"times_arr_14\"\n" +
                "\n" +
                "21:00-22:00\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"is_queue\"\n" +
                "\n" +
                "0\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"occupy_quota\"\n" +
                "\n" +
                "1\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g\n" +
                "Content-Disposition: form-data; name=\"sign_and_login_type\"\n" +
                "\n" +
                "1\n" +
                "------WebKitFormBoundaryqgcYEAGsqV5oE88g--\n";
        httpPost.setEntity(new StringEntity(body,"UTF-8"));
        //3.发送请求
//        HttpResponse postResponse = client.execute(httpPost);
        HttpResponse postResponse = null;
        try {
            postResponse = client.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.获取结果
        assert postResponse != null;
        String postResult = EntityUtils.toString(postResponse.getEntity());
        int first = postResult.lastIndexOf("<div class=\"text\">") + 17;
        int last = postResult.lastIndexOf("<script type=\"text/javascript\">") - 17;
        String s = shi2.equals("-1") ? "" : "-时间" + shi2;
        if(last < first || last < 0){
            System.out.println(reverseDay + "-场地" + courtId + "-时间" + shi1 + s + "-time" + sdfTime.format(new Date()) + ":" + postResult);
        }else{
            System.out.println(reverseDay + "-场地" + courtId + "-时间" + shi1 + s + "-time" + sdfTime.format(new Date()) + ":" +postResult.substring(first,last));
        }

        return postResult;
//        return postResult.lastIndexOf("该次提交已失效，请重试(*￣︶￣*)") == -1 &&
//                postResult.lastIndexOf("选择预约对象不在当前预约内，下单失败，请重新选择预约的时间段") == -1 &&
//                postResult.lastIndexOf("存在已过期时间段，下单失败，请重新选择预约的时间段") == -1 &&
//                postResult.lastIndexOf("你预约的时间并非空闲或此时段已经过时了") == -1 &&
//                postResult.lastIndexOf("客户端提示：没有登录，请先登录") == -1 &&
//                postResult.lastIndexOf("每天只可预约1次") == -1 &&
//                postResult.lastIndexOf("你已经预约过该时段了~") == -1;
    }
}
